# 给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。 
# 
#  
# 
#  示例： 
# 二叉树：[3,9,20,null,null,15,7], 
# 
#  
#     3
#    / \
#   9  20
#     /  \
#    15   7
#  
# 
#  返回其层序遍历结果： 
# 
#  
# [
#   [3],
#   [9,20],
#   [15,7]
# ]
#  
#  Related Topics 树 广度优先搜索 二叉树 
#  👍 1044 👎 0
from queue import Queue
from typing import List


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        result = []
        if root is None:
            return result
        q = [root]
        while q:
            level = []
            level_len = len(q)
            for i in range(level_len):
                node = q.pop(0)
                level.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            result.append(level)
        return result


# leetcode submit region end(Prohibit modification and deletion)


def log(*args, **kwargs):
    print(*args, **kwargs)

# 广度优先
# 队列中存一层的元素
# 遍历队列, 扩展下层元素加入队列, 将队列中的本层元素加入结果

    # def levelOrder(self, root: TreeNode) -> List[List[int]]:
    #     result = []
    #     if root is None:
    #         return result
    #     q = [root]
    #     while q:
    #         level = []
    #         level_len = len(q)
    #         for i in range(level_len):
    #             node = q.pop(0)
    #             level.append(node.val)
    #             if node.left:
    #                 q.append(node.left)
    #             if node.right:
    #                 q.append(node.right)
    #         result.append(level)
    #     return result


if __name__ == '__main__':
    s = Solution()
    #     3
    #    / \
    #   9  20
    #     /  \
    #    15   7
    t1 = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
    # [
    #   [3],
    #   [9,20],
    #   [15,7]
    # ]
    r1 = s.levelOrder(t1)
    e1 = [[3], [9, 20], [15, 7]]
    assert r1 == e1, r1
